import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'

let instance = axios.create({
  baseURL: "http://127.0.0.1:8000",
  timeout: 6000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8;'
  }
})

let loading
let requestCounter = 0
const showLoading = () => {
  if (requestCounter == 0 && !loading) {
    loading = ElLoading.service({
      text: "加载中...",
      background: 'rgba(0, 0, 0, 0.7)',
      spinner: 'el-icon-loading'
    })
  }
  requestCounter++
}

const hideLoading = () => {
  requestCounter--
  if (requestCounter == 0) {
    loading.close()
  }
}

instance.interceptors.request.use((config) => {
  showLoading()
  const token = localStorage.getItem('token')
  token && (config.headers.Authorization = token)
  return config
}, (error) => {
  Promise.reject(error)
})


instance.interceptors.response.use((response) => {
  hideLoading()
  console.log("response data: ", response.data)
  let token = response.data.token
  if (token) {
    localStorage.setItem("token", token)
  }
  return response
}, (error) => {
  if (error.response && error.response.status) {
    const status = error.response.status
    let message
    switch (status) {
      case 400:
        message = '请求错误';
        break;
      case 401:
        message = '请求错误';
        break;
      case 404:
        message = '请求地址出错';
        break;
      case 408:
        message = '请求超时';
        break;
      case 500:
        message = '服务器内部错误!';
        break;
      case 501:
        message = '服务未实现!';
        break;
      case 502:
        message = '网关错误!';
        break;
      case 503:
        message = '服务不可用!';
        break;
      case 504:
        message = '网关超时!';
        break;
      case 505:
        message = 'HTTP版本不受支持';
        break;
      default:
        message = '请求失败'
    }
    ElMessage.error(message)
    console.log("error:", error)
    return Promise.reject(error)
  }
  console.log("error:", error)
  return Promise.reject(error)
})

export default instance